﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Threading;
using System.Data.SqlClient;
using System.Runtime.InteropServices;
using System.IO;
using System.Diagnostics;

namespace HDS
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        #region 共用变量
        #region API
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out   int ID);
        #endregion
        string ufdata = string.Empty;//数据库名
        static StringBuilder sb1;
        static StringBuilder sb2;
        static StringBuilder sb3;
        SqlConnection con;
        private static string configFilePath = Application.StartupPath + "\\config.ini";
        bool aOK = true;//主表插入标识
        int aOKCount = 0;//主表插入成功次数
        bool bOK = true;//子表插入标识
        int bOKCount = 0;//子表插入成功次数
        int errorInfo = 0;//错误编码
        int rdidA = 0;//入库单主表最大id
        int rdidB = 0;//入库单子表最大id
        int errCount = 0;//检测时发生错误的次数
        string errString = string.Empty;//检测时发生错误的原因
        string ddh = string.Empty;//订单号
        string dataXX = string.Empty;//日期
        string ckId = string.Empty;//仓库编码
        string chId = string.Empty;//存货编码
        string cllb = string.Empty;//材料类别
        string bmbm = string.Empty;//部门编码
        string ywybm = string.Empty;//业务员编码
        string xmbm = string.Empty;//项目编码
        double qty;//数量
        string price = string.Empty;//单价
        string total = string.Empty;//总价
        string poId = string.Empty;//订单主表标识
        string posId = string.Empty;//订单子表标识
        string cWhCode = string.Empty;//入库单仓库
        int logType = 0;//日志类型
        int billType = 0;//单据类型
        string logTime = string.Empty;//记录日志时间
        #endregion

        #region 采购入库单变量
        string rkdh = string.Empty;//入库单号
        string rklb = string.Empty;//入库类别
        string gysId = string.Empty;//供应商编码
        string fpId = string.Empty;//发票号 自定义项
        string hongchong = string.Empty;//红冲 自定义项
        string zdr = string.Empty;//制单人
        string shr = string.Empty;//审核人
        string ktbm = string.Empty;//课题编码
        #endregion

        #region 销售出库单变量
        string ckdh = string.Empty;//出库单号
        string xmId = string.Empty;//项目编码
        string khId = string.Empty;//客户编码
        #endregion

        private void Form1_Load(object sender, EventArgs e)
        {
            sb1 = new StringBuilder(255);
            sb2 = new StringBuilder(255);
            sb3 = new StringBuilder(255);
            GetPrivateProfileString("config", "server", "", sb1, 255, configFilePath);
            GetPrivateProfileString("config", "id", "", sb2, 255, configFilePath);
            GetPrivateProfileString("config", "pwd", "", sb3, 255, configFilePath);
            LoadZT();
            LoadYear();
        }

        #region 获取帐套和年度
        private void LoadZT()
        {
            string sql = "select cacc_id,cacc_name from ua_account";
            SqlCommand com = new SqlCommand(sql, DBHelper.con);
            DBHelper.con.Open();
            using (SqlDataReader sdr = com.ExecuteReader())
            {
                while (sdr.Read())
                {
                    string id = sdr["cacc_id"].ToString();
                    string name = sdr["cacc_name"].ToString();
                    lsZT.Items.Add(id + "_" + name);
                }
            }
            DBHelper.con.Close();
        }

        private void LoadYear()
        {
            string sql = "select distinct(iyear) from ua_account_sub where iyear <> 9999";
            SqlCommand com = new SqlCommand(sql, DBHelper.con);
            DBHelper.con.Open();
            using (SqlDataReader sdr = com.ExecuteReader())
            {
                while (sdr.Read())
                {
                    string year = sdr["iyear"].ToString();
                    lsYear.Items.Add(year);
                }
            }
            DBHelper.con.Close();
        }
        #endregion

        #region excel导入dgv
        /// <summary>
        /// 获取指定 Excel 文件中工作表的数据。默认取第一个工作表。
        /// </summary>
        /// <param name="fileName">Excel 的文件名</param>
        /// <returns></returns>
        private DataTable GetDataFromExcel(String fileName, string HDR)
        {
            string sheetName = GetExcelSheetNameByIndex(fileName, 0);
            if (!String.IsNullOrEmpty(sheetName))
            {
                string commandText = String.Format("SELECT * FROM [{0}]", sheetName);
                return ExecuteDataTable(fileName, commandText, HDR);
            }
            return null;
        }

        /// <summary>
        /// 获取 Excel 文件中指定索引的工作表名称
        /// </summary>
        /// <param name="fileName">Excel 的文件名</param>
        /// <param name="sheetIndex">要获取的索引</param>
        /// <returns></returns>
        private String GetExcelSheetNameByIndex(String fileName, int sheetIndex)
        {
            string connectionString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", fileName);
            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                try
                {
                    conn.Open();
                    DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    return schemaTable.Rows.Count > sheetIndex
                        ? schemaTable.Rows[sheetIndex]["TABLE_NAME"].ToString()
                        : String.Empty;
                }
                catch (OleDbException e)
                {
                    if (e.ErrorCode == -2147467259)
                    {
                        MessageBox.Show("文件为只读状态,无法打开");
                    }
                }
                return null;
            }
        }
        /// <summary>
        /// 获取指定 Excel 文件中工作表的数据。
        /// </summary>
        /// <param name="fileName">Excel 的文件名</param>
        /// <param name="commandText">查询 SQL </param>
        private DataTable ExecuteDataTable(String fileName, String commandText, string HDR)
        {
            string connectionString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=1\";", fileName);
            using (OleDbDataAdapter da = new OleDbDataAdapter(commandText, connectionString))
            {
                DataSet ds = new DataSet();
                da.Fill(ds);
                return ds.Tables[0];
            }
        }
        #endregion

        #region po按钮
        /// <summary>
        /// PO浏览按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPOUrl_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofdZT = new OpenFileDialog();
            ofdZT.Filter = "Microsoft Excel 97-2003 工作表(*.xls)|*.xls";
            if (ofdZT.ShowDialog() == DialogResult.OK)
            {
                txtPOUrl.Text = ofdZT.FileName;
            }
            else
            {
                return;
            }
            DataTable importData = GetDataFromExcel(ofdZT.FileName, "no");
            dgvZT.DataSource = importData;
            txtPOUrl.Enabled = false;
            btnPOCheck.Enabled = true;
        }

        /// <summary>
        /// PO检测按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPOCheck_Click(object sender, EventArgs e)
        {
            try
            {
                if (lsZT.SelectedItem.ToString() == "")
                {
                }
                else
                {
                    ufdata += "ufdata_" + lsZT.SelectedItem.ToString().Substring(0, 3);
                }
            }
            catch
            {
                MessageBox.Show("没有选择帐套！");
                return;
            }
            try
            {
                if (lsYear.SelectedItem.ToString() == "")
                {
                }
                else
                {
                    ufdata += "_" + lsYear.SelectedItem.ToString();
                }
            }
            catch
            {
                MessageBox.Show("没有选择年度！");
                return;
            }
            if (dgvZT.Rows.Count < 1)
            {
                MessageBox.Show("没有选择数据源！");
                return;
            }
            if (!dgvZT.Rows[0].Cells[1].Value.ToString().Equals("订单号") || !dgvZT.Rows[0].Cells[2].Value.ToString().Equals("采购类型") ||
                    !dgvZT.Rows[0].Cells[3].Value.ToString().Equals("入库单号") || !dgvZT.Rows[0].Cells[4].Value.ToString().Equals("入库日期") ||
                    !dgvZT.Rows[0].Cells[5].Value.ToString().Equals("材料类别") || !dgvZT.Rows[0].Cells[6].Value.ToString().Equals("入库类别") ||
                    !dgvZT.Rows[0].Cells[7].Value.ToString().Equals("供应商编码") || !dgvZT.Rows[0].Cells[8].Value.ToString().Equals("供应商名称") ||
                    !dgvZT.Rows[0].Cells[9].Value.ToString().Equals("部门编码") || !dgvZT.Rows[0].Cells[10].Value.ToString().Equals("部门名称") ||
                    !dgvZT.Rows[0].Cells[11].Value.ToString().Equals("项目编码") || !dgvZT.Rows[0].Cells[12].Value.ToString().Equals("业务员编码") ||
                    !dgvZT.Rows[0].Cells[13].Value.ToString().Equals("业务员名称") || !dgvZT.Rows[0].Cells[14].Value.ToString().Equals("物料编码") ||
                    !dgvZT.Rows[0].Cells[15].Value.ToString().Equals("物料名称") || !dgvZT.Rows[0].Cells[16].Value.ToString().Equals("规格型号") ||
                    !dgvZT.Rows[0].Cells[17].Value.ToString().Equals("计量单位") || !dgvZT.Rows[0].Cells[18].Value.ToString().Equals("数量") ||
                    !dgvZT.Rows[0].Cells[19].Value.ToString().Equals("含税单价") || !dgvZT.Rows[0].Cells[20].Value.ToString().Equals("含税金额") ||
                    !dgvZT.Rows[0].Cells[21].Value.ToString().Equals("无税单价") || !dgvZT.Rows[0].Cells[22].Value.ToString().Equals("无税金额") ||
                    !dgvZT.Rows[0].Cells[23].Value.ToString().Equals("税额") || !dgvZT.Rows[0].Cells[24].Value.ToString().Equals("发票号") ||
                    !dgvZT.Rows[0].Cells[25].Value.ToString().Equals("是否红冲") || !dgvZT.Rows[0].Cells[26].Value.ToString().Equals("订单付款日期") ||
                    !dgvZT.Rows[0].Cells[27].Value.ToString().Equals("备用字段1") || !dgvZT.Rows[0].Cells[28].Value.ToString().Equals("备用字段2") ||
                    !dgvZT.Rows[0].Cells[29].Value.ToString().Equals("制单人") || !dgvZT.Rows[0].Cells[30].Value.ToString().Equals("验收人（审核人）") ||
                    !dgvZT.Rows[0].Cells[0].Value.ToString().Equals("仓库编码"))
            {
                MessageBox.Show("文件格式检测不正确");
                return;
            }
            else
            {
                if (dgvZT.Rows.Count > 1000)
                {
                    //如果数据量大 删除dgv第一行(EXCEL表头)
                    DataRowView drv = dgvZT.Rows[0].DataBoundItem as DataRowView;
                    drv.Delete();
                }
                else
                {
                    //如果数据量小 重新读取Excel,Excel表头作为DGV表头
                    DataTable importData = GetDataFromExcel(txtPOUrl.Text, "yes");
                    dgvZT.DataSource = importData;
                }
                billType = 1;
                logType = 1;
                logTime = DateTime.Parse(DateTime.Now.ToString()).ToString("yyyyMMddhhmmss");
                btnPOCheck.Enabled = false;
            }
            pbLoad.Maximum = dgvZT.Rows.Count;
            bgwPOCheck.RunWorkerAsync();
        }

        /// <summary>
        /// PO导入按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPOOK_Click(object sender, EventArgs e)
        {
            logType = 2;
            pbLoad.Value = 0;
            logTime = DateTime.Parse(DateTime.Now.ToString()).ToString("yyyyMMddhhmmss");
            bgwPO.RunWorkerAsync();
        }
        #endregion

        #region po检测线程
        private void bgwPOCheck_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            while (worker.CancellationPending == false)
            {
                for (int i = 0; i < dgvZT.Rows.Count; i++)
                {
                    worker.ReportProgress(0, i);
                    Thread.Sleep(100);
                }
                bgwPOCheck.CancelAsync();//结束
            }
        }

        private void bgwPOCheck_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            pbLoad.PerformStep();
            int i = (int)e.UserState;
            try
            {
                ddh = dgvZT.Rows[i].Cells[1].Value.ToString().Trim();//获取订单号
                rkdh = dgvZT.Rows[i].Cells[3].Value.ToString().Trim();//获取入库号
                dataXX = dgvZT.Rows[i].Cells[4].Value.ToString().Trim();//获取入库日期
                ckId = dgvZT.Rows[i].Cells[0].Value.ToString().Trim();//获取仓库编码
                rklb = dgvZT.Rows[i].Cells[6].Value.ToString().Trim();//获取入库类别
                gysId = dgvZT.Rows[i].Cells[7].Value.ToString().Trim();//获取供应商编码
                chId = dgvZT.Rows[i].Cells[14].Value.ToString().Trim();//获取存货编码
                qty = Convert.ToDouble(dgvZT.Rows[i].Cells[18].Value);//获取数量
                price = dgvZT.Rows[i].Cells[19].Value.ToString().Trim();//获取单价
                total = dgvZT.Rows[i].Cells[20].Value.ToString().Trim();//获取总价
                fpId = dgvZT.Rows[i].Cells[24].Value.ToString().Trim();//获取发票号
                hongchong = dgvZT.Rows[i].Cells[25].Value.ToString().Trim();//获取红冲
                zdr = dgvZT.Rows[i].Cells[29].Value.ToString().Trim();//获取制单人
                shr = dgvZT.Rows[i].Cells[30].Value.ToString().Trim();//获取审核人
                cllb = dgvZT.Rows[i].Cells[5].Value.ToString().Trim();//获取材料类别
                bmbm = dgvZT.Rows[i].Cells[9].Value.ToString().Trim();//获取部门编码
                ywybm = dgvZT.Rows[i].Cells[12].Value.ToString().Trim();//获取业务员编码
            }
            catch
            {
                MessageBox.Show("获取字段时出现错误");
                btnPOCheck.Enabled = true;
                return;
            }
            if (rkdh == "" || ckId == "" || gysId == "" || chId == "")
            {
                txtInfo.Text += "主要字段出现空值" + "\n";
                errCount++;
            }
            else if (!selectInventory_cinvCode() || !selectWarehouse_cWhCode() || !selectVendor_cVenCode())
            {
                txtInfo.Text += errString + "\n";
                errCount++;
            }
            if (i + 1 == dgvZT.Rows.Count)
            {
                if (errCount < 1)
                {
                    dgvZT.Enabled = false;
                    lsZT.Enabled = false;
                    lsYear.Enabled = false;
                    btnPOOK.Enabled = true;
                    btnPOUrl.Enabled = false;
                    label4.Text = "检测完成,可导入,目前除了'导入'按钮其他都被锁定";
                    MessageBox.Show("检测完成,可导入");
                }
                else
                {
                    label4.Text = "检测完成,不可导入";
                    btnPOCheck.Enabled = true;
                    MessageBox.Show("有" + errCount + "行数据有问题");
                }
            }
            else
            {
                label4.Text = "正在检测数据,大约剩余" + ((Convert.ToInt32(dgvZT.Rows.Count) - i) / 10) + "秒";
            }
        }

        private void bgwPOCheck_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (txtInfo.Text != "")
            {
                btnLog.PerformClick();
                Process.Start("explorer.exe ", Application.StartupPath + "\\CheckLog\\" + "采购入库单\\");
            }
        }
        #endregion

        #region po导入线程
        private void bgwPO_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            while (worker.CancellationPending == false)
            {
                for (int i = 0; i < dgvZT.Rows.Count; i++)
                {
                    worker.ReportProgress(0, i);
                    Thread.Sleep(100);
                }
                bgwPO.CancelAsync();//结束
            }
        }

        private void bgwPO_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            pbLoad.PerformStep();
            int i = (int)e.UserState;
            ddh = dgvZT.Rows[i].Cells[1].Value.ToString().Trim();//获取订单号
            rkdh = dgvZT.Rows[i].Cells[3].Value.ToString().Trim();//获取入库号
            dataXX = dgvZT.Rows[i].Cells[4].Value.ToString().Trim();//获取入库日期
            ckId = dgvZT.Rows[i].Cells[0].Value.ToString().Trim();//获取仓库编码
            rklb = dgvZT.Rows[i].Cells[6].Value.ToString().Trim();//获取入库类别
            gysId = dgvZT.Rows[i].Cells[7].Value.ToString().Trim();//获取供应商编码
            chId = dgvZT.Rows[i].Cells[14].Value.ToString().Trim();//获取存货编码
            qty = Convert.ToDouble(dgvZT.Rows[i].Cells[18].Value);//获取数量
            price = dgvZT.Rows[i].Cells[19].Value.ToString().Trim();//获取单价
            total = dgvZT.Rows[i].Cells[20].Value.ToString().Trim();//获取总价
            fpId = dgvZT.Rows[i].Cells[24].Value.ToString().Trim();//获取发票号
            hongchong = dgvZT.Rows[i].Cells[25].Value.ToString().Trim();//获取红冲
            zdr = dgvZT.Rows[i].Cells[29].Value.ToString().Trim();//获取制单人
            shr = dgvZT.Rows[i].Cells[30].Value.ToString().Trim();//获取审核人
            cllb = dgvZT.Rows[i].Cells[5].Value.ToString().Trim();//获取材料类别
            bmbm = dgvZT.Rows[i].Cells[9].Value.ToString().Trim();//获取部门编码
            ywybm = dgvZT.Rows[i].Cells[12].Value.ToString().Trim();//获取业务员编码
            if (i == 0)//第一行
            {
                maxMRDid();
                maxDRDid();
                setID_RD();
            }
            if (selectRdRecord_cCode())//如果入库单存在
            {
                insert_RdRecords(i, 1);//插入存货
            }
            else
            {
                insert_RdRecord(i, 1);//新增入库单
                insert_RdRecords(i, 1);
            }
            if (i + 1 == dgvZT.Rows.Count)//最后一行
            {
                maxMRDid();
                maxDRDid();
                setID_RD();
            }
        }

        private void bgwPO_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btnLog.PerformClick();
            Process.Start("explorer.exe ", Application.StartupPath + "\\Log\\" + "采购入库单\\");
            MessageBox.Show("导入执行完毕,检测到Excel共" + dgvZT.Rows.Count + "行,成功导入" + bOKCount + "行,其中创建" + aOKCount + "张订单");
        }
        #endregion

        #region so按钮
        /// <summary>
        /// so浏览按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSOUrl_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofdZT = new OpenFileDialog();
            ofdZT.Filter = "Microsoft Excel 97-2003 工作表(*.xls)|*.xls";
            if (ofdZT.ShowDialog() == DialogResult.OK)
            {
                txtSOUrl.Text = ofdZT.FileName;
            }
            else
            {
                return;
            }
            DataTable importData = GetDataFromExcel(ofdZT.FileName, "no");
            dgvZT.DataSource = importData;
            txtSOUrl.Enabled = false;
            btnSOCheck.Enabled = true;
        }

        /// <summary>
        /// so检测按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSOCheck_Click(object sender, EventArgs e)
        {
            try
            {
                if (lsZT.SelectedItem.ToString() == "")
                {
                }
                else
                {
                    ufdata += "ufdata_" + lsZT.SelectedItem.ToString().Substring(0, 3);
                }
            }
            catch
            {
                MessageBox.Show("没有选择帐套！");
                return;
            }
            try
            {
                if (lsYear.SelectedItem.ToString() == "")
                {
                }
                else
                {
                    ufdata += "_" + lsYear.SelectedItem.ToString();
                }
            }
            catch
            {
                MessageBox.Show("没有选择年度！");
                return;
            }
            if (dgvZT.Rows.Count < 1)
            {
                MessageBox.Show("没有选择数据源！");
                return;
            }
            if (dgvZT.Rows[1].Cells[1].Value.ToString().Equals("销售出库"))
            {
                MessageBox.Show("检测判定为 销售出库 模板");
                billType = 2;
            }
            else if (dgvZT.Rows[1].Cells[1].Value.ToString().Equals("领料出库"))
            {
                MessageBox.Show("检测判定为 领料出库 模板");
                billType = 3;
            }
            else
            {
                MessageBox.Show("检测模板类型失败！");
                return;
            }
            if (billType == 2)
            {
                if (!dgvZT.Rows[0].Cells[0].Value.ToString().Equals("订单号") || !dgvZT.Rows[0].Cells[1].Value.ToString().Equals("出库类别") ||
                        !dgvZT.Rows[0].Cells[2].Value.ToString().Equals("销售类型") || !dgvZT.Rows[0].Cells[3].Value.ToString().Equals("出库单号") ||
                        !dgvZT.Rows[0].Cells[5].Value.ToString().Equals("材料类别") || !dgvZT.Rows[0].Cells[6].Value.ToString().Equals("仓库编码") ||
                        !dgvZT.Rows[0].Cells[7].Value.ToString().Equals("客户编码") || !dgvZT.Rows[0].Cells[8].Value.ToString().Equals("客户名称") ||
                        !dgvZT.Rows[0].Cells[9].Value.ToString().Equals("部门编码") || !dgvZT.Rows[0].Cells[10].Value.ToString().Equals("部门名称") ||
                        !dgvZT.Rows[0].Cells[11].Value.ToString().Equals("项目编码") || !dgvZT.Rows[0].Cells[12].Value.ToString().Equals("业务员编码") ||
                        !dgvZT.Rows[0].Cells[13].Value.ToString().Equals("业务员名称") || !dgvZT.Rows[0].Cells[14].Value.ToString().Equals("物料编码") ||
                        !dgvZT.Rows[0].Cells[15].Value.ToString().Equals("物料名称") || !dgvZT.Rows[0].Cells[16].Value.ToString().Equals("规格型号") ||
                        !dgvZT.Rows[0].Cells[17].Value.ToString().Equals("计量单位") || !dgvZT.Rows[0].Cells[18].Value.ToString().Equals("数量") ||
                        !dgvZT.Rows[0].Cells[19].Value.ToString().Equals("单价") || !dgvZT.Rows[0].Cells[20].Value.ToString().Equals("金额") ||
                        !dgvZT.Rows[0].Cells[4].Value.ToString().Equals("单据日期"))
                {
                    MessageBox.Show("文件格式检测不正确");
                    return;
                }
            }
            if (billType == 3)
            {
                if (!dgvZT.Rows[0].Cells[0].Value.ToString().Equals("订单号") || !dgvZT.Rows[0].Cells[1].Value.ToString().Equals("出库类别") ||
                            !dgvZT.Rows[0].Cells[2].Value.ToString().Equals("销售类型") || !dgvZT.Rows[0].Cells[3].Value.ToString().Equals("出库单号") ||
                            !dgvZT.Rows[0].Cells[5].Value.ToString().Equals("材料类别") || !dgvZT.Rows[0].Cells[6].Value.ToString().Equals("仓库编码") ||
                            !dgvZT.Rows[0].Cells[7].Value.ToString().Equals("客户编码") || !dgvZT.Rows[0].Cells[8].Value.ToString().Equals("客户名称") ||
                            !dgvZT.Rows[0].Cells[9].Value.ToString().Equals("部门编码") || !dgvZT.Rows[0].Cells[10].Value.ToString().Equals("部门名称") ||
                            !dgvZT.Rows[0].Cells[11].Value.ToString().Equals("课题编码") || !dgvZT.Rows[0].Cells[12].Value.ToString().Equals("课题名称") ||
                            !dgvZT.Rows[0].Cells[14].Value.ToString().Equals("业务员名称") || !dgvZT.Rows[0].Cells[15].Value.ToString().Equals("物料编码") ||
                            !dgvZT.Rows[0].Cells[16].Value.ToString().Equals("物料名称") || !dgvZT.Rows[0].Cells[17].Value.ToString().Equals("规格型号") ||
                            !dgvZT.Rows[0].Cells[18].Value.ToString().Equals("计量单位") || !dgvZT.Rows[0].Cells[19].Value.ToString().Equals("数量") ||
                            !dgvZT.Rows[0].Cells[20].Value.ToString().Equals("单价") || !dgvZT.Rows[0].Cells[21].Value.ToString().Equals("金额") ||
                            !dgvZT.Rows[0].Cells[4].Value.ToString().Equals("单据日期") || !dgvZT.Rows[0].Cells[13].Value.ToString().Equals("业务员编码"))
                {
                    MessageBox.Show("文件格式检测不正确");
                    return;
                }
            }
            if (dgvZT.Rows.Count > 1000)
            {
                //如果数据量大 删除dgv第一行(EXCEL表头)
                DataRowView drv = dgvZT.Rows[0].DataBoundItem as DataRowView;
                drv.Delete();
            }
            else
            {
                //如果数据量小 重新读取Excel,Excel表头作为DGV表头
                DataTable importData = GetDataFromExcel(txtSOUrl.Text, "yes");
                dgvZT.DataSource = importData;
            }
            logType = 2;
            logTime = DateTime.Parse(DateTime.Now.ToString()).ToString("yyyyMMddhhmmss");
            btnSOCheck.Enabled = false;
            pbLoad.Maximum = dgvZT.Rows.Count;
            bgwSOCheck.RunWorkerAsync();
        }

        /// <summary>
        /// so导入按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSOOK_Click(object sender, EventArgs e)
        {
            logType = 2;
            pbLoad.Value = 0;
            logTime = DateTime.Parse(DateTime.Now.ToString()).ToString("yyyyMMddhhmmss");
            bgwSO.RunWorkerAsync();
        }
        #endregion

        #region so检测线程
        private void bgwSOCheck_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            while (worker.CancellationPending == false)
            {
                for (int i = 0; i < dgvZT.Rows.Count; i++)
                {
                    worker.ReportProgress(0, i);
                    Thread.Sleep(100);
                }
                bgwSOCheck.CancelAsync();//结束
            }
        }

        private void bgwSOCheck_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            pbLoad.PerformStep();
            int i = (int)e.UserState;
            try
            {
                ddh = dgvZT.Rows[i].Cells[0].Value.ToString().Trim();//获取订单号
                ckdh = dgvZT.Rows[i].Cells[3].Value.ToString().Trim();//获取出库号
                dataXX = dgvZT.Rows[i].Cells[4].Value.ToString().Trim();//获取出库日期
                ckId = dgvZT.Rows[i].Cells[6].Value.ToString().Trim();//获取仓库编码
                khId = dgvZT.Rows[i].Cells[7].Value.ToString().Trim();//获取客户编码
                cllb = dgvZT.Rows[i].Cells[5].Value.ToString().Trim();//材料类别
                bmbm = dgvZT.Rows[i].Cells[9].Value.ToString().Trim();//获取部门编码
                if (billType == 2)
                {
                    xmId = dgvZT.Rows[i].Cells[11].Value.ToString().Trim();//获取项目编码
                    ywybm = dgvZT.Rows[i].Cells[12].Value.ToString().Trim();//获取业务员编码
                    chId = dgvZT.Rows[i].Cells[14].Value.ToString().Trim();//获取存货编码
                    qty = Convert.ToDouble(dgvZT.Rows[i].Cells[18].Value);//获取数量
                    price = dgvZT.Rows[i].Cells[19].Value.ToString().Trim();//获取单价
                    total = dgvZT.Rows[i].Cells[20].Value.ToString().Trim();//获取总价
                }
                if (billType == 3)
                {
                    ktbm = dgvZT.Rows[i].Cells[11].Value.ToString().Trim();//获取项目编码
                    ywybm = dgvZT.Rows[i].Cells[13].Value.ToString().Trim();//获取业务员编码
                    chId = dgvZT.Rows[i].Cells[15].Value.ToString().Trim();//获取存货编码
                    qty = Convert.ToDouble(dgvZT.Rows[i].Cells[19].Value);//获取数量
                    price = dgvZT.Rows[i].Cells[20].Value.ToString().Trim();//获取单价
                    total = dgvZT.Rows[i].Cells[21].Value.ToString().Trim();//获取总价
                }
            }
            catch
            {
                MessageBox.Show("获取字段时出现错误");
                btnPOCheck.Enabled = true;
                return;
            }
            if (ckdh == "" || ckId == "" || khId == "" || chId == "")
            {
                txtInfo.Text += "主要字段出现空值" + "\n";
                errCount++;
            }
            else if (!selectInventory_cinvCode() || !selectWarehouse_cWhCode() || !selectCustomer_cCusCode())
            {
                txtInfo.Text += errString + "\n";
                errCount++;
            }
            if (i + 1 == dgvZT.Rows.Count)
            {
                if (errCount < 1)
                {
                    dgvZT.Enabled = false;
                    lsZT.Enabled = false;
                    lsYear.Enabled = false;
                    btnSOOK.Enabled = true;
                    btnSOUrl.Enabled = false;
                    label4.Text = "检测完成,可导入,目前除了'导入'按钮其他都被锁定";
                    MessageBox.Show("检测完成,可导入");
                }
                else
                {
                    label4.Text = "检测完成,不可导入";
                    btnSOCheck.Enabled = true;
                    MessageBox.Show("有" + errCount + "行数据有问题");
                }
            }
            else
            {
                label4.Text = "正在检测数据,大约剩余" + ((Convert.ToInt32(dgvZT.Rows.Count) - i) / 10) + "秒";
            }
        }

        private void bgwSOCheck_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (txtInfo.Text != "")
            {
                btnLog.PerformClick();
                if (billType == 2)
                {
                    Process.Start("explorer.exe ", Application.StartupPath + "\\CheckLog\\" + "销售出库单\\");
                }
                else
                {
                    Process.Start("explorer.exe ", Application.StartupPath + "\\CheckLog\\" + "其他出库单\\");
                }
            }
        }
        #endregion

        #region so导入线程
        private void bgwSO_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            while (worker.CancellationPending == false)
            {
                for (int i = 0; i < dgvZT.Rows.Count; i++)
                {
                    worker.ReportProgress(0, i);
                    Thread.Sleep(100);
                }
                bgwSO.CancelAsync();//结束
            }
        }

        private void bgwSO_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            pbLoad.PerformStep();
            int i = (int)e.UserState;
            ddh = dgvZT.Rows[i].Cells[0].Value.ToString().Trim();//获取订单号
            ckdh = dgvZT.Rows[i].Cells[3].Value.ToString().Trim();//获取出库号
            dataXX = dgvZT.Rows[i].Cells[4].Value.ToString().Trim();//获取出库日期
            ckId = dgvZT.Rows[i].Cells[6].Value.ToString().Trim();//获取仓库编码
            khId = dgvZT.Rows[i].Cells[7].Value.ToString().Trim();//获取客户编码
            cllb = dgvZT.Rows[i].Cells[5].Value.ToString().Trim();//材料类别
            bmbm = dgvZT.Rows[i].Cells[9].Value.ToString().Trim();//获取部门编码
            if (billType == 2)
            {
                xmId = dgvZT.Rows[i].Cells[11].Value.ToString().Trim();//获取项目编码
                ywybm = dgvZT.Rows[i].Cells[12].Value.ToString().Trim();//获取业务员编码
                chId = dgvZT.Rows[i].Cells[14].Value.ToString().Trim();//获取存货编码
                qty = Convert.ToDouble(dgvZT.Rows[i].Cells[18].Value);//获取数量
                price = dgvZT.Rows[i].Cells[19].Value.ToString().Trim();//获取单价
                total = dgvZT.Rows[i].Cells[20].Value.ToString().Trim();//获取总价
            }
            if (billType == 3)
            {
                ktbm = dgvZT.Rows[i].Cells[11].Value.ToString().Trim();//获取课题编码
                ywybm = dgvZT.Rows[i].Cells[13].Value.ToString().Trim();//获取业务员编码
                chId = dgvZT.Rows[i].Cells[15].Value.ToString().Trim();//获取存货编码
                qty = Convert.ToDouble(dgvZT.Rows[i].Cells[19].Value);//获取数量
                price = dgvZT.Rows[i].Cells[20].Value.ToString().Trim();//获取单价
                total = dgvZT.Rows[i].Cells[21].Value.ToString().Trim();//获取总价
            }
            if (i == 0)//第一行
            {
                maxMRDid();
                maxDRDid();
                setID_RD();
            }
            if (selectRdRecord_cCode())//如果入库单存在
            {
                insert_RdRecords(i, billType);//插入存货
            }
            else
            {
                insert_RdRecord(i, billType);//新增入库单
                insert_RdRecords(i, billType);
            }
            if (i + 1 == dgvZT.Rows.Count)//最后一行
            {
                maxMRDid();
                maxDRDid();
                setID_RD();
            }
        }

        private void bgwSO_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btnLog.PerformClick();
            if (billType == 2)
            {
                Process.Start("explorer.exe ", Application.StartupPath + "\\Log\\" + "销售出库单\\");
            }
            else
            {
                Process.Start("explorer.exe ", Application.StartupPath + "\\Log\\" + "其他出库单\\");
            }
            MessageBox.Show("导入执行完毕,检测到Excel共" + dgvZT.Rows.Count + "行,成功导入" + bOKCount + "行,其中创建" + aOKCount + "张订单");
        }
        #endregion

        #region 检测编码
        /// <summary>
        /// 查询存货编码是否存在
        /// </summary>
        /// <returns></returns>
        private bool selectInventory_cinvCode()
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select cinvCode from Inventory where cinvCode='{0}'", chId);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                if (Convert.ToString(com.ExecuteScalar()).Equals(chId))
                {
                    return true;
                }
                else
                {
                    errString = "存货编码不存在";
                }
            }
            catch
            {
                errString = "存货编码不存在";
            }
            finally
            {
                con.Close();
            }
            return false;
        }

        /// <summary>
        /// 查询仓库编码是否存在
        /// </summary>
        /// <returns></returns>
        private bool selectWarehouse_cWhCode()
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select cWhCode from Warehouse where cWhCode='{0}'", ckId);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                if (Convert.ToString(com.ExecuteScalar()).Equals(ckId))
                {
                    return true;
                }
                else
                {
                    errString = "仓库编码不存在";
                }
            }
            catch
            {
                errString = "仓库编码不存在";
            }
            finally
            {
                con.Close();
            }
            return false;
        }

        /// <summary>
        /// 查询供应商编码是否存在
        /// </summary>
        /// <returns></returns>
        private bool selectVendor_cVenCode()
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select cVenCode from Vendor where cVenCode='{0}'", gysId);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                if (Convert.ToString(com.ExecuteScalar()).Equals(gysId))
                {
                    return true;
                }
                else
                {
                    errString = "供应商编码不存在";
                }
            }
            catch
            {
                errString = "供应商编码不存在";
            }
            finally
            {
                con.Close();
            }
            return false;
        }

        /// <summary>
        /// 查询客户编码是否存在
        /// </summary>
        /// <returns></returns>
        private bool selectCustomer_cCusCode()
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select cCusCode from Customer where cCusCode='{0}'", khId);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                if (Convert.ToString(com.ExecuteScalar()).Equals(khId))
                {
                    return true;
                }
                else
                {
                    errString = "客户编码不存在";
                }
            }
            catch
            {
                errString = "客户编码不存在";
            }
            finally
            {
                con.Close();
            }
            return false;
        }

        /// <summary>
        /// 查询入库单是否存在
        /// </summary>
        /// <returns></returns>
        private bool selectRdRecord_cCode()
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select cwhcode from RdRecord where ccode = '{0}' and cwhcode='{1}' and csource='存货'", rkdh, ckId);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                try
                {
                    cWhCode = com.ExecuteScalar().ToString();
                }
                catch
                {
                    cWhCode = string.Empty;
                }
            }
            catch
            {
            }
            finally
            {
                con.Close();
            }
            if (cWhCode != "")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 获取最大id，回写
        /// <summary>
        /// 获取入库单主表最大ID
        /// </summary>
        private void maxMRDid()
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = "select max(id) from RdRecord";
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                try
                {
                    rdidA = Convert.ToInt32(com.ExecuteScalar());
                }
                catch
                {
                    rdidA = 0;
                }
            }
            catch
            {
            }
            finally
            {
                con.Close();
            }
        }

        /// <summary>
        /// 获取入库单子表最大ID
        /// </summary>
        private void maxDRDid()
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = "select max(autoid) from RdRecords";
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                try
                {
                    rdidB = Convert.ToInt32(com.ExecuteScalar());
                }
                catch
                {
                    rdidB = 0;
                }
            }
            catch
            {
            }
            finally
            {
                con.Close();
            }
        }

        /// <summary>
        /// 采购入库单ID回写
        /// </summary>
        private void setID_RD()
        {
            try
            {
                string sql = string.Format("update UA_Identity Set iFatherId='{0}',iChildId='{1}' Where cAcc_Id='{2}' And cVouchType='rd'", rdidA, rdidB, ufdata);
                SqlCommand com = new SqlCommand(sql, DBHelper.con);
                DBHelper.con.Open();
                com.ExecuteNonQuery();
            }
            catch
            {
            }
            finally
            {
                DBHelper.con.Close();
            }
        }
        #endregion

        #region 插入订单
        /// <summary>
        /// 插入采购入库单主表
        /// </summary>
        /// <param name="i"></param>
        /// <param name="type">1采购入库单 2销售出库单</param>
        private void insert_RdRecord(int i, int type)
        {
            aOK = true;
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            rdidA++;
            string sql = string.Empty;
            try
            {
                switch (type)
                {
                    case 1:
                        sql = string.Format(@"Insert Into Rdrecord(id,brdflag,cvouchtype,cbustype,csource,cbuscode,cwhcode,ddate,ccode,crdcode,
                                            cdepcode,cpersoncode,cptcode,cvencode,cordercode,carvcode,cbillcode,cmemo,chandler,caccounter,cmaker,
                                            cdefine1,cdefine2,cdefine3,cdefine4,cdefine5,cdefine6,cdefine7,cdefine8,cdefine9,cdefine10,dveridate,
                                            vt_id,bisstqc,cchkperson,cdefine11,cdefine12,cdefine13,cdefine14,cdefine15,cdefine16,imquantity,cstcode,
                                            ccuscode,darvdate,cchkcode,dchkdate,gspcheck,ipurorderid,ipurarriveid,iproorderid,iarriveid,isalebillid,
                                            dkeepdate,bpufirst,biafirst) Values ('{10}',1,'01','普通采购','存货',NULL,'{0}','{1}','{2}',NULL,
                                            '{14}','{15}',NULL,'{4}',NULL,NULL,NULL,NULL,'{11}',NULL,'{6}','{7}','{8}','{13}',NULL,NULL,NULL,0,NULL,NULL,
                                            NULL,'{12}',27,0,NULL,NULL,NULL,NULL,NULL,NULL,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                            NULL,NULL,0,0)
                                            ", ckId, dataXX, rkdh, null, gysId, null, zdr, cllb, fpId, null, rdidA, shr, dataXX, hongchong,bmbm,ywybm);
                        break;
                    case 2:
                        sql = string.Format(@"Insert Into Rdrecord(id,brdflag,cvouchtype,cbustype,csource,cbuscode,cwhcode,ddate,ccode,crdcode,
                                            cdepcode,cpersoncode,cptcode,cvencode,cordercode,carvcode,cbillcode,cmemo,chandler,caccounter,cmaker,
                                            cdefine1,cdefine2,cdefine3,cdefine4,cdefine5,cdefine6,cdefine7,cdefine8,cdefine9,cdefine10,dveridate,
                                            vt_id,bisstqc,cchkperson,cdefine11,cdefine12,cdefine13,cdefine14,cdefine15,cdefine16,imquantity,cstcode,
                                            ccuscode,darvdate,cchkcode,dchkdate,gspcheck,ipurorderid,ipurarriveid,iproorderid,iarriveid,isalebillid,
                                            dkeepdate,bpufirst,biafirst) Values ('{3}',0,'32','普通销售','存货',NULL,'{0}','{1}','{2}',NULL,
                                            NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,'{5}','{6}','{7}',NULL,NULL,NULL,0,NULL,NULL,
                                            NULL,Null,87,0,NULL,NULL,NULL,NULL,NULL,NULL,0,0,NULL,'{4}',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                            NULL,NULL,0,0)
                                            ", ckId, dataXX, ckdh, rdidA, khId, ddh, cllb, xmbm);
                        break;
                    case 3:
                        sql = string.Format(@"Insert Into Rdrecord(id,brdflag,cvouchtype,cbustype,csource,cbuscode,cwhcode,ddate,ccode,crdcode,
                                            cdepcode,cpersoncode,cptcode,cvencode,cordercode,carvcode,cbillcode,cmemo,chandler,caccounter,cmaker,
                                            cdefine1,cdefine2,cdefine3,cdefine4,cdefine5,cdefine6,cdefine7,cdefine8,cdefine9,cdefine10,dveridate,
                                            vt_id,bisstqc,cchkperson,cdefine11,cdefine12,cdefine13,cdefine14,cdefine15,cdefine16,imquantity,cstcode,
                                            ccuscode,darvdate,cchkcode,dchkdate,gspcheck,ipurorderid,ipurarriveid,iproorderid,iarriveid,isalebillid,
                                            dkeepdate,bpufirst,biafirst) Values ('{3}',0,'09','其他出库','存货',NULL,'{0}','{1}','{2}',NULL,
                                            NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,{5}'',NULL,NULL,NULL,NULL,NULL,0,NULL,NULL,
                                            NULL,Null,85,0,NULL,NULL,NULL,NULL,NULL,NULL,0,0,NULL,'{4}',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                            NULL,NULL,0,0)
                                            ", ckId, dataXX, ckdh, rdidA, khId, ktbm);
                        break;
                }
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {
                errorInfo = e.Number;
                aOK = false;
            }
            finally
            {
                con.Close();
            }
            i = i + 2;
            if (isok == 0)
            {
                aOK = false;
                aOKCount--;
                txtInfo.Text += ufdata + "新订单创建失败,原因" + errorInfo + "【" + i + "】" + "\n";
                label4.Text = ufdata + "新订库单创建失败";
            }
            else
            {
                aOKCount++;
                txtInfo.Text += ufdata + "新订单创建成功【" + i + "】" + "\n";
                label4.Text = ufdata + "新订单创建成功";
            }
        }

        /// <summary>
        /// 插入采购入库单子表
        /// </summary>
        /// <param name="i"></param>
        /// <param name="type">1采购入库单 2销售出库单</param>
        private void insert_RdRecords(int i, int type)
        {
            if (aOK == false)//如果主表插入失败
            {
                return;
            }
            bOK = true;
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            rdidB++;
            string sql = string.Empty;
            try
            {
                switch (type)
                {
                    case 1:
                        sql = string.Format(@"Insert Into Rdrecords(autoid,id,cinvcode,cbarcode,cassunit,inum,iquantity,iunitcost,iprice,
                                            iaprice,ipunitcost,ipprice,cbatch,cvouchcode,cfree1,cfree2,cfree3,cfree4,cfree5,cfree6,cfree7,
                                            cfree8,cfree9,cfree10,inquantity,innum,dmadedate,iflag,dsdate,itax,isnum,isquantity,imoney,
                                            isoutquantity,isoutnum,ifnum,ifquantity,dvdate,cposition,cdefine22,cdefine23,cdefine24,cdefine25,
                                            cdefine26,cdefine27,cdefine28,cdefine29,cdefine30,cdefine31,cdefine32,cdefine33,cdefine34,cdefine35,
                                            cdefine36,cdefine37,impoids,itrids,icheckids,citem_class,citemcode,iarrsid,iposid,facost,cname,
                                            citemcname,imassdate,cbvencode,cinvouchcode,cgspstate,ccheckcode,icheckidbaks,crejectcode,irejectids,
                                            ccheckpersoncode,dcheckdate) Values ({0},{1},'{2}',NULL,NULL,0,'{3}','{4}','{5}','{6}',NULL,NULL,NULL,
                                            NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,'{7}',0,NULL,0,NULL,0,0,0,0,0,0,0,0,NULL,NULL,
                                            NULL,NULL,NULL,NULL,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                            NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL)
                                            ", rdidB, rdidA, chId, qty, price, total, total, 0, null);
                        break;
                    case 2:
                        sql = string.Format(@"Insert Into Rdrecords(autoid,id,cinvcode,cbarcode,cassunit,inum,iquantity,iunitcost,iprice,
                                            iaprice,ipunitcost,ipprice,cbatch,cvouchcode,cfree1,cfree2,cfree3,cfree4,cfree5,cfree6,cfree7,
                                            cfree8,cfree9,cfree10,inquantity,innum,dmadedate,iflag,dsdate,itax,isnum,isquantity,imoney,
                                            isoutquantity,isoutnum,ifnum,ifquantity,dvdate,cposition,cdefine22,cdefine23,cdefine24,cdefine25,
                                            cdefine26,cdefine27,cdefine28,cdefine29,cdefine30,cdefine31,cdefine32,cdefine33,cdefine34,cdefine35,
                                            cdefine36,cdefine37,impoids,itrids,icheckids,citem_class,citemcode,iarrsid,iposid,facost,cname,
                                            citemcname,imassdate,cbvencode,cinvouchcode,cgspstate,ccheckcode,icheckidbaks,crejectcode,irejectids,
                                            ccheckpersoncode,dcheckdate) Values ({0},{1},'{2}',NULL,NULL,0,'{3}','{4}','{5}','{6}',NULL,NULL,NULL,
                                            NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,'{7}',0,NULL,0,NULL,0,0,0,0,0,0,0,0,NULL,NULL,
                                            NULL,NULL,NULL,NULL,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                            NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL)
                                            ", rdidB, rdidA, chId, qty, price, total, total, 0, null);
                        break;
                    case 3:
                        sql = string.Format(@"Insert Into Rdrecords(autoid,id,cinvcode,cbarcode,cassunit,inum,iquantity,iunitcost,iprice,
                                            iaprice,ipunitcost,ipprice,cbatch,cvouchcode,cfree1,cfree2,cfree3,cfree4,cfree5,cfree6,cfree7,
                                            cfree8,cfree9,cfree10,inquantity,innum,dmadedate,iflag,dsdate,itax,isnum,isquantity,imoney,
                                            isoutquantity,isoutnum,ifnum,ifquantity,dvdate,cposition,cdefine22,cdefine23,cdefine24,cdefine25,
                                            cdefine26,cdefine27,cdefine28,cdefine29,cdefine30,cdefine31,cdefine32,cdefine33,cdefine34,cdefine35,
                                            cdefine36,cdefine37,impoids,itrids,icheckids,citem_class,citemcode,iarrsid,iposid,facost,cname,
                                            citemcname,imassdate,cbvencode,cinvouchcode,cgspstate,ccheckcode,icheckidbaks,crejectcode,irejectids,
                                            ccheckpersoncode,dcheckdate) Values ({0},{1},'{2}',NULL,NULL,0,'{3}','{4}','{5}','{6}',NULL,NULL,NULL,
                                            NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,'{7}',0,NULL,0,NULL,0,0,0,0,0,0,0,0,NULL,NULL,
                                            NULL,NULL,NULL,NULL,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                            NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL)
                                            ", rdidB, rdidA, chId, qty, price, total, total, 0, null);
                        break;
                }
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {
                errorInfo = e.Number;
                bOK = false;
            }
            finally
            {
                con.Close();
            }
            i = i + 2;
            if (isok == 0)
            {
                bOK = false;
                bOKCount--;
                txtInfo.Text += ufdata + "新订单插入商品" + chId + "失败，原因" + errorInfo + "【" + i + "】" + "\n";
                label4.Text = ufdata + "新订单插入商品" + chId + "失败，原因" + errorInfo;
            }
            else
            {
                bOKCount++;
                txtInfo.Text += ufdata + "新订单插入商品" + chId + "成功【" + i + "】" + "\n";
                label4.Text = ufdata + "新订单插入商品" + chId + "成功";
            }
        }
        #endregion

        /// <summary>
        /// 日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLog_Click(object sender, EventArgs e)
        {
            if (txtInfo.Text == "")
            {
                MessageBox.Show("没有日志！");
                return;
            }
            string s = "\n";
            string s1 = "\r\n";
            string str = this.txtInfo.Text;
            str = str.Replace(s, s1);
            string tempURL = string.Empty;
            string finalURL = string.Empty;
            if (logType == 1)
            {
                if (billType == 1)
                {
                    tempURL = Application.StartupPath + "\\CheckLog\\" + "\\采购入库单\\";
                    Directory.CreateDirectory(tempURL);
                    finalURL = tempURL + "\\" + logTime + ".txt";
                }
                if (billType == 2)
                {
                    tempURL = Application.StartupPath + "\\CheckLog\\" + "\\销售出库单\\";
                    Directory.CreateDirectory(tempURL);
                    finalURL = tempURL + "\\" + logTime + ".txt";
                }
                if (billType == 3)
                {
                    tempURL = Application.StartupPath + "\\CheckLog\\" + "\\其他出库单\\";
                    Directory.CreateDirectory(tempURL);
                    finalURL = tempURL + "\\" + logTime + ".txt";
                }
            }
            else
            {
                if (billType == 1)
                {
                    tempURL = Application.StartupPath + "\\Log\\" + "\\采购入库单\\";
                    Directory.CreateDirectory(tempURL);
                    finalURL = tempURL + "\\" + logTime + ".txt";
                }
                if (billType == 2)
                {
                    tempURL = Application.StartupPath + "\\Log\\" + "\\销售出库单\\";
                    Directory.CreateDirectory(tempURL);
                    finalURL = tempURL + "\\" + logTime + ".txt";
                }
                if (billType == 3)
                {
                    tempURL = Application.StartupPath + "\\Log\\" + "\\其他出库单\\";
                    Directory.CreateDirectory(tempURL);
                    finalURL = tempURL + "\\" + logTime + ".txt";
                }
            }
            try
            {
                File.WriteAllText(finalURL, str);//保存日志
                txtInfo.Text = "";
            }
            catch
            {
                MessageBox.Show("日志文件生成失败！");
            }
        }
    }
}